package cn.sixmillions.yuqueblog.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.http.HttpUtil;
import cn.sixmillions.yuqueblog.config.YuQueProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 图片处理
 *
 * @author lbw
 * @date 2021-12-12
 */
@Controller
@RequestMapping("/api/image")
@Slf4j
@Api(value = "Image", tags = "图片")
public class ImageController {

    /**
     * 缓存存放路径
     */
    @Autowired
    private YuQueProperties conf;

    /**
     * 对防盗链的图片进行下载缓存
     *
     * @param url      图片url，
     *                 例如：https://cdn.nlark.com/yuque/0/2021/png/1678756/1637041442475-41d73d07-9582-4be3-90f1-7ad5a4c08886.png
     * @param response
     * @throws IOException
     */
    @GetMapping
    @ApiOperation(value = "下载语雀图片到本地", notes = "返回图片")
    public void downloadImg(String url, HttpServletResponse response) throws IOException {
        String filePath = conf.getImgCachePath();
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        // 缓存是否存在
        if (!FileUtil.exist(filePath + fileName)) {
            log.info("不存在{}图片缓存，先从语雀下载本地", fileName);
            // 将文件下载后保存在E盘，返回结果为下载文件大小
            long size = HttpUtil.downloadFile(url, FileUtil.file(filePath));
            log.info("Download size: {}", size);
        }
        FileReader fileReader = new FileReader(filePath + fileName);
        byte[] buffer = fileReader.readBytes();
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        try (OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
            out.write(buffer);
            out.flush();
        } catch (Exception e) {
            log.error("图片下载异常");
            throw e;
        }
    }
}
